
/*
描述：用户个人信息编辑视图组件，用于修改和保存用户个人资料信息
完成人：吴悠
完成时间: 2025/04/27
*/



<script setup lang="ts">
import { useRouter } from 'vue-router';
import HeaderComponent from "../../components/HomeView/HeaderComponent.vue";
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import MyNavbar from "@/components/UserView/MyNavbar.vue";
import QuestionComponent from "@/components/HomeView/QuestionComponent.vue";
import RecentQuestion from "@/components/HomeView/RecentQuestion.vue";

const router = useRouter();
const formRef = ref<FormInstance>();

const goToUser = () => {
  // router.push('/user');
};


interface UserInfo {
  username: string;
  password?: string;
  email: string;
  nickname: string;
  avatar: string;
  enrtydate?: string;
  age: number | null;
  gender: number | null;
  introduction: string;
  phone: string;
  type?: number;
}


const editForm = ref<UserInfo>({
  username: '',
  email: '',
  nickname: '',
  avatar: '',
  age: null,
  gender: null,
  introduction: '',
  phone: '',
});


const rules = reactive<FormRules<UserInfo>>({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
  age: [
    { type: 'number', message: '年龄必须为数字值', trigger: 'blur' },
    { validator: (rule, value:number, callback) => {
        if (value !== null && (value < 0 || value > 150)) {
          callback(new Error('请输入有效的年龄 (0-150)'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  introduction: [
    { max: 200, message: '个人简介不能超过200字', trigger: 'blur' },
  ],
});


const fetchUserInfo = async () => {
  const userId = localStorage.getItem('id');
  const token = localStorage.getItem('token');

  if (!userId || !token) {
    ElMessage.error('用户未登录或认证信息丢失');
    router.push('/login'); // Redirect to login if no ID or token
    return;
  }

  try {
    const response = await axios.get(`http://localhost:8089/user/getUserInfo?id=${userId}`, {
      headers: {
        'token': token
      }
    });
    if (response.data.code === 1) {
      // 获取后端的数据绑定到表单上
      const userData = response.data.data;
      console.log("userData",userData);
      editForm.value = {
        ...editForm.value, // Keep existing structure
        username: userData.username || '',
        email: userData.email || '',
        nickname: userData.nickname || '',
        avatar: userData.avatar || '',
        age: userData.age === undefined || userData.age === null ? null : Number(userData.age),
        gender: userData.gender === undefined || userData.gender === null ? null : Number(userData.gender),
        introduction: userData.introduction || '',
        phone: userData.phone || '',
      };
    } else {
      ElMessage.error(response.data.msg || '获取用户信息失败');
    }
  } catch (error) {
    ElMessage.error('获取用户信息时发生网络错误');
  }
};

onMounted(() => {
  fetchUserInfo();
});

const saveProfile = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const token = localStorage.getItem('token');
      const userId = localStorage.getItem('id'); // Needed for the request body
      if (!token || !userId) {
        ElMessage.error('认证信息丢失，请重新登录');
        router.push('/login');
        return;
      }

      try {
        const payload = {
          ...editForm.value, //先解构
          id: userId,
          age: editForm.value.age === null ? null : Number(editForm.value.age),
          gender: editForm.value.gender === null ? null : Number(editForm.value.gender),
        };

        const response = await axios.post('http://localhost:8089/user/updateUserInfo', payload, {
          headers: {
            'token': token,
            'Content-Type': 'application/json'
          }
        });

        if (response.data.code === 1) {
          ElMessage.success('用户信息保存成功！');
          if (editForm.value.nickname) localStorage.setItem('username', editForm.value.nickname);
          if (editForm.value.avatar) localStorage.setItem('avatar', editForm.value.avatar);
          router.push('/user');
        } else {
          ElMessage.error(response.data.msg || '保存用户信息失败');
        }
      } catch (error) {
        console.error('保存用户信息错误:', error);
        ElMessage.error('保存用户信息时发生网络错误');
      }
    } else {
      ElMessage.error('请检查表单输入项');
      return false;
    }
  });
};


</script>

<template>
  <el-container>
    <HeaderComponent/>
    <el-container>
      <el-aside width="20%">
        <div class="sidebar-menu-left">
          <MyNavbar :now-page="4" />
        </div>

      </el-aside>
      <el-main class="body">
        <div class="editInfo">

          <el-form :model="editForm" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px" class="elform">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="editForm.nickname" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" />
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="editForm.age" type="number" />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model.number="editForm.gender">
                <el-radio :value="0">女生</el-radio>
                <el-radio :value="1">男生</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="个人简介" prop="introduction">
              <el-input v-model="editForm.introduction" type="textarea" />
            </el-form-item>
            <el-form-item class="button-group-item">
              <el-button type="primary" @click="saveProfile">保存</el-button>
              <el-button @click="goToUser">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
      <el-aside width="20%">
        <div class="sidebar-menu-right">
          <RecentQuestion/>
        </div>
      </el-aside>
    </el-container>
  </el-container>
</template>


<style scoped>

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input[type="text"],
input[type="email"],
textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

textarea {
  min-height: 100px;
  resize: vertical;
}



button:hover {
  opacity: 0.9;
}

.editInfo{
  background-color: white;
  border-radius: 8px;
  width: 80%;
  padding: 20px;
}

.elform{
  margin: 0 auto;
}


.button-group-item .el-form-item__content {
  justify-content: center;
}


.body{
  display: flex;
  flex-direction: column;  /* 垂直排列 */
  align-items: center;     /* 水平居中（交叉轴方向） */
  height: 100%;
  padding: 84px 20px 20px 20px;
}

.sidebar-menu-left{
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;  /* 元素脱离文档流，相对于浏览器窗口固定定位 */
  top: 84px;
  height: 100vh;
  margin-left: 5%;
}
.sidebar-menu-right{
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;  /* 元素脱离文档流，相对于浏览器窗口固定定位 */
  top: 84px;
  height: 100vh;
}
</style>
